package zut.wework.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import zut.wework.api.WorkWXAPI;
import zut.wework.api.WxApi;
import zut.wework.utils.HttpClientUtil;
import zut.wework.utils.JsonUtil;
import zut.wework.utils.WXAPIUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


/**
 * 校历应用
 * @author: Mr.Liu
 * @create: 2022-05-22 19:03
 */
@Slf4j
@Controller()
@RequestMapping("/sc")
public class SCController {

    @Autowired
    private WxApi wxApi;


    public static final String URI = "";

    /**
     * 校历入口
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/in")
    public String in(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        //设置contentType，解决中文乱码

        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            System.out.println("没有！！！");
            String redirect_uri = java.net.URLEncoder.encode("http://www.xhxlcloud.com:8080/sc/auth", "utf-8");
            return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwe35a821cb91d6024&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base&state=#wechat_redirect";
        } else {


            for (Cookie aCookie : cookies) {
                String name = aCookie.getName();
                String value = aCookie.getValue();
                System.out.println(name+":"+value);
            }
        }
        return "redirect:https://www.baidu.com";
    }


    /**
     * 权限获取
     * @param code
     * @param response
     * @return
     */
    @RequestMapping( "/auth")
    public String addCookies(@RequestParam(value = "code") String code, HttpServletResponse response){
        //判断url 合法性
        log.info("code:{}", code);
        String getUserInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + wxApi.getAccessToken(WorkWXAPI.SC_SECRET) + "&code=" + code;
        Map<String, Object> userInfo = new HashMap<>();

        //发送请求获得用户信息
        userInfo = JsonUtil.toMap(HttpClientUtil.get(getUserInfoUrl));
        log.info("userInfo:{}", userInfo);
        //验证用户信息
        //设置contentType，解决中文乱码
        response.setContentType("text/html;charset=utf-8");

        // 创建一个 cookie对象
        Cookie cookie = new Cookie("userId", (String) userInfo.get("UserId"));
        cookie.setMaxAge(60 * 60); // 7天过期

        //将cookie对象加入response响应
        response.addCookie(cookie);

        return "redirect:http://www.xhxlcloud.com:8080/sc/in";
    }

}
